package com.hpq.common.interceptor;

import com.hpq.common.exception.HttpStatusEnum;
import com.hpq.user.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.Optional;

/**
 * token认证拦截器
 */
@Order(-2)
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private LoginService loginService;
    public static final String ATTRIBUTE_UID = "uid";
    public static final String HEADER_AUTHORIZATION = "Authorization";
    public static final String AUTHENTICATION_PREFIX = "Bearer ";

    /**
     * 前置拦截器
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String token = getToken(request);
        Long uid = loginService.getValidUid(token);
        if(Objects.nonNull(uid)){
            //处于登录态
            request.setAttribute(ATTRIBUTE_UID, uid);
        }else{
            //未登录
            boolean isPublicURI = isPublicURI(request);
            if(!isPublicURI){
                //返回401登录失效
                HttpStatusEnum.sendErrorMessage(response, HttpStatusEnum.UNAUTHORIZED);
                return false;
            }
        }
        return true;
    }

    /**
     * 判断是否是公开接口
     * @param request
     * @return
     */
    private  boolean isPublicURI(HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        String[] split = requestURI.split("/");
         return split.length>3&&split[3].equals("public");
    }

    /**
     * 获取token
     * @param request
     * @return
     */
    private String  getToken(HttpServletRequest request) {
        String authorization = request.getHeader(HEADER_AUTHORIZATION);
        return Optional.ofNullable(authorization)
                .filter(a -> a.startsWith(AUTHENTICATION_PREFIX))
                .map(a -> a.replaceFirst(AUTHENTICATION_PREFIX, ""))
                .orElse(null);


    }


}
